package com.mindainfo.groundwave.server.device.dao.impl;

import com.mindainfo.groundwave.server.device.bean.EventReport;
import com.mindainfo.groundwave.server.device.dao.IEventReportDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Created by MD-01 on 2017/6/13.
 */
@Repository
public class EventReportDaoImpl implements IEventReportDao{

    @Resource
    private JdbcTemplate template;

    @Override
    public List<EventReport> query(Date date, int state) {

        StringBuffer sb = new StringBuffer();

        sb.append(" select id,door_id,time,event,state from ");
        sb.append(" ( ");
        sb.append(" select id,door_id,time,event,state, ");
        sb.append(" @rn:=if(@doorId=door_id,@rn+1,1) rn, ");
        sb.append(" @doorId:=door_id from event_report ");
        sb.append(" JOIN (SELECT @doorId := NULL, @rn := 0) AS vars ");
        sb.append(" where state = ? and time > ? ");
        sb.append(" order by door_id desc,time desc ");
        sb.append(" ) a where a.rn = 1 ");

        String sql = sb.toString();
        return template.query(sql, new RowMapper<EventReport>() {
            @Override
            public EventReport mapRow(ResultSet rs, int rowNum) throws SQLException {
                EventReport report = new EventReport();
                report.setEvent(rs.getString("event"));
                report.setId(rs.getInt("id"));
                report.setDoorId(rs.getInt("door_id"));
                report.setTime(new Date(rs.getTimestamp("time").getTime()));
                report.setState(rs.getInt("state"));
                return report;
            }
        },state,new Timestamp(date.getTime()));
    }

    @Override
    public void updateReport(String ids) {

        String sql = "update event_report set state = 1 where id in ("+ids+")";
        template.update(sql);
    }
}
